//
// Created by LiuYou on 2021/8/2.
//
/**
 * @brief 父子进程之间通过mmap()进行通信。
 */


#include <cstdio>
#include <cstdlib>
#include <sys/mman.h>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>


#define MEM_SIZE 1024


int main() {
    void* pVoid = mmap( nullptr, MEM_SIZE, PROT_READ | PROT_WRITE,
                        MAP_SHARED | MAP_ANONYMOUS, -1, SEEK_SET );
    if (pVoid == MAP_FAILED) {
        std::perror( "mmap()" );
        std::exit( 1 );
    }
    char* ptr = static_cast<char*>(pVoid);

    pid_t pid = fork();
    if (pid < 0) {
        std::perror( "fork()" );
        munmap( pVoid, MEM_SIZE );
        std::exit( 1 );
    }

    // 子进程写
    if (pid == 0) {
        strcpy( ptr, "Hello!" );
        munmap( pVoid, MEM_SIZE );
        std::exit( 0 );
    } else {
        // 父进程读
        wait( nullptr );
        puts( ptr );
        munmap( pVoid, MEM_SIZE );
        exit( 0 );

    }


}